/*
 * boot.S - bootsector 
 *
 * Copyright (C) 2009 by TanMenglong <tanmenglong@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include<boot.h>

.code16
.section .text
.globl _start
_start:
	jmp after_BPB
	nop
	.include "bpb_fat12.S"
	
after_BPB:
	cli

real_mode:
	#initialize %ds and %ss
	xorw %ax,%ax
	movw %ax,%ds
	movw %ax,%ss

	#setup stack
	movw REAL_STACKSEG,%sp
	movw %sp,%bp
	
	sti
	
	#set video mode
	movw $0x0003,%ax
	int $0x10
	
	MSG(sector_msg1)
	/* reset disk */
	xorb %ah,%ah	//Function number=0
	xorb %dl,%dl	//Drive number,O=a,1=2nd floppy
	int $0x13
	
	jnb disk_success /* check */
	MSG(sector_msg4)
	hlt
	_endless_loop2:jmp _endless_loop2
	disk_success:
	MSG(sector_msg3)
	_endless_loop:jmp _endless_loop

sector_msg1:
	.asciz "bootsector: looking for a loader... "
sector_msg2:
	.asciz "found\n\r"
sector_msg3:
	.asciz "not found\n\r"
sector_msg4:
	.asciz "reset disk error!\n\r"
sector_test:
	.asciz "test!\n\r"

.globl test
test:
	push %bp
	mov %sp,%bp
	MSG(sector_test)
	leave
	ret

display:
	push %bp
	mov %sp,%bp
	push %ax
	push %bx

	cld
	movb $0xe,%ah	/* use BIOS interrupt 10,e */
	movb $0xf,%bl	/* font color */
	display_start:
	lodsb
	orb %al,%al
	jz display_end
	int $0x10
	jmp display_start
	display_end:

	pop %bx
	pop %ax
	leave
	ret

/*
 * read cl sectors begin with ax sector
 */
read_sector:
	push %bp
	mov %sp,%bp
	sub $2,%sp	/* leave 2 bytes space to store number of sectors */
	movb %cl,-2(%bp)
	pushw %bx	/* save %bx */
	mov BPB_SecPerTrk,%bl
	div %bl
	inc %ah
	mov %ah,%cl
	mov %al,%dh
	shr %al
	mov %al,%ch
	and $1,%dh
	popw %bx	/* restore %bx */
	mov BS_DrvNum,%dl
_go_on_reading:
	mov $2,%ah
	mov -2(%bp),%al
	int $13
	jc _go_on_reading

	add $2,%sp
	mov %bp,%sp
	pop %bp
	ret

.org 510
.word 0xaa55
